package gui;

import java.util.EnumSet;
import java.util.GregorianCalendar;

import msjcalendar.Pattern;
import msjcalendar.WeeklyPattern;
import msjcalendar.YearlyPattern;
import enums.DayEnum;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TabItem;

/**
 * @author sebastian
 *
 */
public class PatternComposite extends Composite {

	/**
	 * 
	 */
	private Label durationLabel;
	/**
	 * 
	 */
	private Label frequencyLabel;
	/**
	 * set duartion.
	 */
	private Text durationText;
	/**
	 * set frequency.
	 */
	private Text frequencyText;
	/**
	 * change weekly oder yearly pattern.
	 */
	private TabFolder patternTabFolder;
	/**
	 * 
	 */
	private WeeklyPatternComposite weekly;
	/**
	 * 
	 */
	private YearlyPatternComposite yearly;
	
	/**
	 * button for endless repeating event.
	 */
	private Button endlessButton;
	/**
	 * 
	 */
	private Label endlessLabel;
	
	/**
	 * @param parent parent composite
	 * @param style SWT-Style
	 */
	public PatternComposite(final Composite parent, final int style) {
		super(parent, style);
		FormLayout layout = new FormLayout();
		this.setLayout(layout);
		
		this.durationLabel = new Label(this, SWT.LEFT);
		this.frequencyLabel = new Label(this, SWT.LEFT);
		this.durationText = new Text(this, SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
		this.frequencyText = new Text(this, SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
		this.patternTabFolder = new TabFolder(this, SWT.TOP);
		this.weekly = new WeeklyPatternComposite(this.patternTabFolder, SWT.NONE);
		this.yearly = new YearlyPatternComposite(this.patternTabFolder, SWT.NONE);
		
		this.endlessLabel = new Label(this, SWT.NONE);
		FormData data = new FormData();
		data.top = new FormAttachment(0, 10);
		data.left = new FormAttachment(0, 0);
		this.endlessLabel.setText("Endless:");

		this.endlessButton = new Button(this, SWT.CHECK);
		data = new FormData();
		data.top = new FormAttachment(0, 4);
		data.right = new FormAttachment(100, 0);
		endlessButton.setLayoutData(data);
		this.endlessButton.addSelectionListener(new SelectionListener() {
			
			@Override
			public void widgetSelected(final SelectionEvent arg0) {
				if (endlessButton.getSelection()) {
					durationText.setEnabled(false);
					durationText.setText("0");
				} else {
					if (frequencyText.getEnabled()) {
						durationText.setEnabled(true);
					}
				}
			}
			
			@Override
			public void widgetDefaultSelected(final SelectionEvent arg0) {
			}
		});
		
		this.durationLabel.setText("Duration:");
		data = new FormData();
		data.top = new FormAttachment(this.endlessButton, 6);
		data.left = new FormAttachment(0, 0);
		durationLabel.setLayoutData(data);
		
		data = new FormData();
		data.top = new FormAttachment(this.endlessButton, 4);
		data.right = new FormAttachment(100, 0);
		data.left = new FormAttachment(this.durationLabel, 40);
		this.durationText.setLayoutData(data);
		
		this.frequencyLabel.setText("Frequency:");
		data = new FormData();
		data.top = new FormAttachment(this.durationText, 7);
		data.left = new FormAttachment(0, 0);
		this.frequencyLabel.setLayoutData(data);
		
		data = new FormData();
		data.top = new FormAttachment(this.durationText, 5);
		data.right = new FormAttachment(100, 0);
		data.left = new FormAttachment(this.durationLabel, 40);
		this.frequencyText.setLayoutData(data);
		
		data = new FormData();
		data.top = new FormAttachment(this.frequencyText, 5);
		data.left = new FormAttachment(0, 0);
		data.right = new FormAttachment(100, 0);
		data.bottom = new FormAttachment(100, 0);
		this.patternTabFolder.setLayoutData(data);
		
		TabItem tab0 = new TabItem(this.patternTabFolder, SWT.HORIZONTAL);
		tab0.setText("Weekly");
		tab0.setControl(this.weekly);
		
		TabItem tab1 = new TabItem(this.patternTabFolder, SWT.HORIZONTAL);
		tab1.setText("Yearly");
		tab1.setControl(this.yearly);
		
		Listener verification =  new Listener() {
		      public void handleEvent(final Event e) {
			        String string = e.text;
			        char[] chars = new char[string.length()];
			        string.getChars(0, chars.length, chars, 0);
			        for (int i = 0; i < chars.length; i++) {
			          if (!('0' <= chars[i] && chars[i] <= '9')) {
			            e.doit = false;
			            return;
			          }
			        }
			      }
			    };
		
		this.durationText.addListener(SWT.Verify, verification);
		this.frequencyText.addListener(SWT.Verify, verification);
	}

	/**
	 * @return the parsed pattern of this control
	 */
	public Pattern getPattern() {
		int freq = Integer.parseInt(this.frequencyText.getText());
		int dur = Integer.parseInt(this.durationText.getText());
		
		if (this.patternTabFolder.getSelectionIndex() == 0) {
			return new WeeklyPattern(this.weekly.getWeekDay(), dur, freq);
		} else {
			return new YearlyPattern(dur, freq, this.yearly.getDate());
		}
	}
	
	/**
	 * @param pattern pattern to display
	 */
	public void setPattern(final Pattern pattern) {
		if (pattern == null) {
			EnumSet<DayEnum> set = EnumSet.noneOf(DayEnum.class);
			this.weekly.setWeekDay(set);
			this.yearly.setDate(new GregorianCalendar());
			this.durationText.setText("");
			this.frequencyText.setText("");
		} else {
			this.durationText.setText(String.valueOf(pattern.getDuration()));
			this.frequencyText.setText(String.valueOf(pattern.getFrequency()));
			if (pattern instanceof WeeklyPattern) {
				this.weekly.setWeekDay(((WeeklyPattern) pattern).getWeekDay());
				this.yearly.setDate(new GregorianCalendar());
			} else {
				EnumSet<DayEnum> set = EnumSet.noneOf(DayEnum.class);
				this.weekly.setWeekDay(set);
				this.yearly.setDate(((YearlyPattern) pattern).getDate());
			}
		}
	}
	
	@Override
	public void setEnabled(final boolean b) {
		this.frequencyText.setEditable(b);
		this.durationText.setEditable(b);
		this.weekly.setEnabled(b);
		this.yearly.setEnabled(b);
		this.endlessButton.setEnabled(b);
	}
	
	/**
	 * @return verification-message
	 */
	public String getVerificationMessage() {
		String result = "";
		if (this.durationText.getText().trim().equals("")) {
			result = result.concat("Duration has to be a Value >=0.\n");
		}
		if ((this.frequencyText.getText().trim().equals("")) || (Integer.parseInt(this.frequencyText.getText().trim()) == 0)) {
			result = result.concat("Frequency has to be a Value >0.\n");
		}
		if (!this.weekly.verify() && (this.patternTabFolder.getSelectionIndex() == 0)) {
			result = result.concat("One or more days have to be selected.\n");
		}
		return result;
	}
	
	/**
	 * @return verification
	 */
	public boolean verify() {
		return this.getVerificationMessage().equalsIgnoreCase("");
	}
}
